#!usr/bin/env python
# *- coding:utf-8 -*-
# Andy Create @ 11/19/2019 3:40 PM
from flask import Blueprint, request, session, render_template, redirect, url_for
from flask_excel.utils import SqlHelper

account = Blueprint('account', __name__, template_folder='templates')
sqler = SqlHelper()


@account.route('/login', methods=['GET', 'POST', ], endpoint='login')
def login():
    if request.method == 'GET':
        return render_template('login.html')
    elif request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        sql = "select username, password from User where username = %s;"

        try:
            username, pwd = sqler.fetchone(sql, username)
            if password == pwd:
                session['username'] = username
                session['is_login'] = True
                return redirect(url_for('account.index'))
        except:
            print('No record was fetched')


@account.route('/index', methods=['GET'], endpoint='index')
def index():
    sql = "select id, title, author, price from Book;"
    result = sqler.fetchall(sql)
    books = []
    for book in result:
        data = {}
        data['id'] = book[0]
        data['title'] = book[1]
        data['author'] = book[2]
        data['price'] = book[3]
        books.append(data)
    return render_template('index.html', books=books)
